$(function () {
  page.bind();
  page.getCustomerCode('1');
  page.getCustomerName('1');
  queryCustomers(myTrim($("#search-text").val()), '1');
  page.showModal();
})
var customerNameArr = [];
var customerCodeArr = [];
var toPageParam = '';
var page = {
  bind: function () {
    $("#search-text").keyup(function (event) {
      var searchText = myTrim($("#search-text").val());
      setTimeout(function () {
        queryCustomers(searchText, $("#view").val());
      }, 300);
    });
    $("#search-btn").bind("click", function () {
      queryCustomers(myTrim($("#search-text").val()), $("#view").val());
    });
    //点击切换查看状态按钮
    $("#view").bind("click", function () {
      var view = $("#view").val();
      if (view == "1") {
        view = "0";
      } else {
        view = "1";
      }
      page.getCustomerName(view);
      queryCustomers(myTrim($("#search-text").val()), view);
      $("#view").val(view);
    });
    $("#modalCustomerCode").bind("blur", function () {
      if ($.inArray($(this).val(), customerCodeArr) != -1) {
        $("#modalCustomerCode").val("");
        layer.msg("客户代码已存在", {
          'icon': 2
        });
      };
    });
    $("#modalCustomerName").bind("blur", function () {
      //判断客户名称是否存在
      if ($.inArray($(this).val(), customerNameArr) != -1) {
        $("#modalCustomerName").val("");
        layer.msg("客户名称已存在", {
          'icon': 2
        });
      };
    });
    //模态框点击添加按钮时
    $("#add").bind("click", function () {
  			var customerCode = myTrim($("#modalCustomerCode").val());
  			if (customerCode == "") {
  				layAlert("请填写客户代码");
  				return false;
  			}
  			var customerName = myTrim($("#modalCustomerName").val());
  			console.log(customerName);
  			if (customerName == "") {
  				layAlert("请填写客户名称");
  				return false;
  			}
  			var type = $("#modal_type").val();
  			if (type == "") {
  				layAlert("请选择客户类型");
  				return false;
  			} 
  			var contact = $("#modalContact").val();
  			if (contact == "") {
  				layAlert("请填写联系人");
  				return false;
  			}
  			var password = $("#modalPassword").val();
  			var phone = $("#modalPhone").val();
  			var email = $("#modal-email").val();
  			if(email!="" && /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(email)==false){
  				layAlert("邮箱格式不正确");
  				return false;
  			}
  			var paymentWay = $("#modalPaymentWay").val();
  			if(paymentWay==""){
  				layAlert("请选择付款结算方式");
  				return false;
  			}
  			var fax = $("#modalFax").val();
  			var address = $("#modalAddress").val();
  			ajaxUtil.ajaxRuquest(
  				'basicData/insertCustomer', {
  					'customerCode': customerCode,
  					'customerName': customerName,
  					'type':type,
  					'status': '使用',
  					'contact': contact,
  					'password':password,
  					'phone': phone,
  					'email':email,
  					'fax': fax,
  					'address': address,
  					'paymentWay':paymentWay
  				},
  				function (data) {
  					//点击提交按钮后刷新表
  					
  					dataTable.ajax.reload(null, false);
  					page.getCustomerCode('1');
  					page.getCustomerName($("#view").val());
  					layAlert("插入成功");
  					//如果是从生成物料采购单过来的,就是跳转到新增物料页面
  					if(type!=="2"){
  						toPageParam = customerName;
  					}
  					$("#addCustomerModal").modal("hide");
  					//放在最下面不影响上面执行
  					if(type !=1){
  						page.setOutMaterialCutomerName(customerName);
  					}
  				}
  			)
    });
    //改变客户名称时
    $("#customerName").bind("change", function () {
      var customerId = $("#customerName").val();
      page.getCustomerDetail(customerId);
    });
    $("#modal_type").bind("change",function(){
    	var type = $("#modal_type").val();
    	if(type==="2" || type ==="3"){
    		$("#modalShowPassword").show();
    	}else{
    		$("#modalShowPassword").hide();
    	}
    });
    $("#type").bind("change",function(){
    	var type = $("#type").val();
    	if(type==="2" || type ==="3"){
    		$("#showPassword").show();
    	}else{
    		$("#showPassword").hide();
    	}
    });
    //点击+客户名称按钮时
    $("#addCustomerBtn").bind("click", function () {
      $("#addCustomerNameTr").show("slow");
    });
    //点击添加按钮时
    $("#addCustomerNameBtn").bind("click", function () {
      var addCustomerName = $("#addCustomerName").val();
      if (addCustomerName == "") {
        layAlert("请输入要添加的客户名称");
        return false;
      } else {
        $("#addCustomerNameTr").hide("slow");
        $("#customerName").append("<option value=" + addCustomerName + ">" + addCustomerName + "</option>");
        $("#customerName option[value='" + addCustomerName + "']").attr("selected", "selected");
        //				page.getCustomerDetail(addCustomerName);
      }
    });
    //点击提交按钮时
    $("#reportBtn").bind("click", function () {
      var customerName = myTrim($("#customerName option:selected").text());
      if (customerName == "请选择") {
        layAlert("请选择客户名称");
        return false;
      }
      var type = $("#type").val();
      if (type == "") {
        layAlert("请选择客户类型");
        return false;
      }
      var contact = $("#contact").val();
      if (contact == "") {
        layAlert("请填写联系人");
        return false;
      }
      var password = $("#password").val();
      var phone = $("#phone").val();
//      if (phone == "") {
//        layAlert("请填写联系电话");
//        return false;
//      }
      var email = $("#email").val();
      if (email != "" && /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(email) == false) {
        layAlert("邮箱格式不正确");
        return false;
      }
      var paymentWay = $("#paymentWay").val();
      if (paymentWay == "") {
        layAlert("请选择付款结算方式");
        return false;
      }
      var status = $("#status").val();
      if (status == "请选择") {
        layAlert("请选择状态");
        return false;
      }
      //update
      ajaxUtil.ajaxRuquest(
        'basicData/updateCustomer',
        page.insertAndUpdateParam(),
        function (data) {
          //点击提交按钮后刷新表
          dataTable.ajax.reload(null, false);
          page.getCustomerName($("#view").val());
          layAlert("修改成功");
        }
      );
    });

    $('#addCustomerModal').on('hide.bs.modal', function () {
      page.toPage();
    });
  },
  setOutMaterialCutomerName: function (cutomerName) {
    $(".customerName").each(function () {
      $(this).next().prepend("<option value='" + cutomerName + "' />");
    });
    try {
      mateialPage.pageCoustomArray.push(cutomerName);
    } catch (error) {

    }
  },
  //跳转 
  toPage: function () {
    var data = GetRequest();
    if (data === null) {
      sessionStorage.removeItem("customerName");
      return;
    }

    var customerName = toPageParam;
    if (customerName !== ''){
    	sessionStorage.setItem("customerName", customerName);
    }
    if (data.addCustomer === "1") {
      location.href = "purchaseOrder/feddingBill/index.html?addCustomer=2";
    } else if (data.saveNewMaterial === "1") {
      location.href = "purchaseOrder/companyMaterialTable/index.html?addCustomer=2";
    } else if (data.add === '2') {
      location.href = "purchaseOrder/companyMaterialTable/index.html?addCustomer=3";
    }

  },
  showModal: function () {
    var data = GetRequest();
    if (data !== null) {
      $("#addCustomerModal").modal("show");
    }
  },
  //客户表获取客户代码
  getCustomerCode: function (view) {
    ajaxUtil.ajaxRuquest('basicData/getCustomerCode', {
        'view': view
      },
      function (data) {
        for (var i = 0; i < data.length; i++) {
          //只加入状态为使用的客户名称
          if (view == 1 && data[i].customerCode != null && data[i].customerCode != '' && $.inArray(data[i].customerCode, customerCodeArr) == -1) {
            customerCodeArr.push(data[i].customerCode);
          }
        }
      });
  },
  //从客户表获得客户名称
  getCustomerName: function (view) {
    ajaxUtil.ajaxRuquest('basicData/getCustomerName', {
      'view': view,
      'type': 3
    }, function (data) {
      var html = "<option>请选择</option>";
      for (var i = 0; i < data.length; i++) {
        html = html + "<option value=" + data[i].id + ">" + data[i].customerName + "</option>";
        //只加入状态为使用的客户名称
        if (view == 1 && $.inArray(data[i].customerName, customerNameArr) == -1) {
          customerNameArr.push(data[i].customerName);
        }
      }
      $("#customerName").html("");
      $("#customerName").append(html);
    });
  },
  //获取客户详情
  getCustomerDetail: function (id) {
    ajaxUtil.ajaxRuquest(
      'basicData/getCustomerDetail', {
        'id': id
      },
      function (data) {
        if (data != "") {
          //根据客户名能查找到数据时
          $("#customerCode").val(data[0].customerCode);
          $("#customerName").val(data[0].id);
          $("#type").val(data[0].type);
          $("#status").val(data[0].status);
          $("#contact").val(data[0].contact);
          $("#phone").val(data[0].phone);
          $("#email").val(data[0].email);
          $('#paymentWay').val(data[0].paymentWay);
          $("#fax").val(data[0].fax);
          $("#address").val(data[0].address);
          $("#creater").val(data[0].creater);
          $("#creationTime").val(data[0].creationTime);
          $("#lastModifier").val(data[0].lastModifier);
          $("#lastModifyTime").val(data[0].lastModifyTime);
          $("#sort").val(data[0].sort);
          $("#password").val(data[0].password);
          if(data[0].type===2 || data[0].type ===3){
        	  $("#showPassword").show();
          }else{
        	  $("#showPassword").hide();
          }
        }
      }
    );
  },
  //插入或修改需要的参数
  insertAndUpdateParam: function () {
    var customerCode = $("#customerCode").val();
    var customerName = $("#customerName option:selected").text();
    var type = $("#type").val();
    var status = $("#status").val();
    var id = $("#customerName").val();
    var contact = $("#contact").val();
    var phone = $("#phone").val();
    var email = $("#email").val();
    var fax = $("#fax").val();
    var address = $("#address").val();
    var paymentWay = $("#paymentWay").val();
    var password = $("#password").val();
    var sendData = {
      'id': id,
      'customerCode': customerCode,
      'customerName': customerName,
      'type': type,
      'status': status,
      'contact': contact,
      'phone': phone,
      'email': email,
      'fax': fax,
      'address': address,
      'paymentWay': paymentWay,
      'password':password
    }
    return sendData;
  }
}
var tableData = []; //查询客户结果
//查询所有客户
var dataTable;

function queryCustomers(searchText, view) {
  if (searchText != $("#search-text").val()) {
    return;
  }
  if (view == undefined) {
    view = '1';
  }
  $('#queryCustomersTable tbody').unbind("click");
  dataTable = ajaxUtil.dataTablesAjax("queryCustomersTable", 10, "basicData/queryCustomers", {
    'view': view,
    'type': 3,
    'searchText': searchText
  }, [{
      "data": "customerCode"
    },
    {
      "data": "customerName"
    },
    {
      "data": "status"
    }
  ]);
  //行点击事件
  $('#queryCustomersTable tbody').on('click', 'tr', function () {
    var data = dataTable.row(this).data();
    var id = data.id;
    page.getCustomerDetail(id);
  });
  return;
  ajaxUtil.ajaxRuquest(
    "basicData/queryCustomers",
    null,
    function (data) {
      tableData = data;
      //要显示的字段
      var thArray = ["customerCode", "customerName", "status"];
      var html = "<thead><tr><th>客户代码</th><th>客户名称</th><th>状态</th></tr></thead>";
      if (tableData.length > 0) { //生成表体，同样规则
        for (var j = 0; j < tableData.length; j++) {
          html += "<tr onclick='page.getCustomerDetail(\"" + tableData[j]["customerName"] + "\")'>";
          for (var k = 0; k < thArray.length; k++) {
            var xx = thArray[k];
            html += "<td>" + tableData[j][xx] + "</td>"
          }
          html += "</tr>";
        }
      } else {
        html = "没有数据!";
      }
      $("#queryCustomersTable").html("");
      $("#queryCustomersTable").append(html);
    }
  );
}
//获取请求参数
function GetRequest() {
  var url = location.search; //获取url中"?"符后的字串
  var theRequest = {};
  if (url.indexOf("?") !== -1) {
    var str = url.substr(1);
    strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
    }
  } else {
    theRequest = null;
  }
  return theRequest;
}